/**
 * @author 带只拖鞋去流浪
 */
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// const {Buffer} = require('buffer');
const clc = require('cli-color');
const iconv = require('iconv-lite');
const querystring = require('querystring');


const server = http.createServer((req,res)=>{
    // console.log(req.url);
    // console.log(req.method);
    const {method} = req;
    switch (method) {
        case "GET":
            get(req,res);
            break;
    
        default:
            // 禁止访问
            res.statusCode = 403;
            res.end('not be allowed.');
            break;
    }
});

function get(req,res){
    // url?param1=value1&param2=value2
    const [url, paramsString] = req.url.split(/\?/);
    const params = querystring.parse(paramsString);

    switch (url) {
        case '/':
            const html = fs.readFileSync(path.resolve(__dirname,'../public/index.html'),{encoding: 'utf-8'});
            res.end(html);
            break;

        case '/command':
            let str = '', flag = true;
            const {cmd} = params;
            try {
                str = execSync(cmd);
            } catch (error) {
                const {status, signal, output, pid, stdout, stderr} = error;
                str = stderr;
                flag = false;
                // console.log(Object.keys(error));
                // console.error(error);
            }
            // if(str instanceof Buffer) str = str.toString(); 编码不匹配
            res.write(JSON.stringify({flag, str: iconv.decode(str, 'gb2312') }));
            res.end();
            break;
    
        default:
            break;
    }
}

server.listen(3000, ()=>{
    console.log(clc.green.underline('http://localhost:3000/'));
    console.log(clc.green.underline('http://127.0.0.1:3000/'));
});